<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysUserTch;
use Admin\Models\user\XhsysUserHistory;
use Admin\Models\user\XhsysUserstud;
use Complex\Exception;
use Helpers\Device;
use Helpers\Main;
use Helpers\Template;
use Helpers\User;
use Helpers\UserPower;
use Helpers\Assets;
use Admin\Models\user\XhsysUser;
use Helpers\XhException;
use Modules\Power;
use Modules\School;
use Services\Auth;
use Services\UserManage;

class UserController extends ControllerBase
{

    private $userEnum = [
        'bDisable'  => [0 => '否', 1 => '是'],
        'bHistory'  => [0 => '否', 1 => '是'],
        'bCompany'  => [0 => '否', 1 => '是'],
        'iUserSex'  => [0 => '未知', 1 => '男', 2 => '女'],
        'iType'      => [0 => '不计入考核' , 1 => '计入考核' ],
        'iPoorLevel' => [0 => '未提交' , 1 => '待审核', 2 => '通过', 3 => '未通过' ],
        'iDevSource' => [0 => '否', 1 => '是'],
        'bEbook' => [0 => '无', 1 => '购买', 2 => '租用', 3 => '借用', 4 => '自购'],
    ];
    private $repeatEnum = [
        'bEnable'   => [0 => '禁用', 1 => '正常']
    ];

    private function getUserEnum()
    {
        $this->userEnum['iUserType']  = XhsysEnum::getEnumByNodeName('用户类型');
        $this->userEnum['iGradeCode'] = XhsysEnum::getEnumByNodeName('年级');
        $this->userEnum['iCurGrade'] = XhsysEnum::getEnumByNodeName('年级');
        $this->userEnum['iProficiency'] = XhsysEnum::getEnumByNodeName('熟练程度');
        $this->userEnum['iSubject'] = XhsysEnum::getEnumByNodeName('学科');
        $this->userEnum['sSubjects[]'] = XhsysEnum::getEnumByNodeName('学科');
//        $this->userEnum['iSchoolId']  = ['' => '--请选择--'] + XhschoolInfo::getSchoolSupportArray();
        return $this->userEnum;
    }

    /**
     * 用户列表页面
     *
     * create by ck 20160315
     * modify by ck 20160630    优化
     * modify by ck 20160824    结构更改
     * modify by ck 20161010    js压缩集合，权限增加
     * modify by ck 20161031    添加同步用户按钮
     */
    public function indexAction()
    {
        $this->view->pick('user/userList');
        $userType = $this->request->getQuery('iUserType', 'int');
//        $this->view->setTemplateBefore('listForm');//->pick('user/userList');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/user/userList.js');
        if (!UserPower::checkUserPower('User_UserList')) {
            return $this->sendViewError('无查看权限');
        }
        $listSearchArr = $listButtonArr = $power = [];
        if (UserPower::checkUserPower('User_UserList_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus'];
        }
        if (UserPower::checkUserPower('User_UserList_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_enable', 'text' => '启用', 'icon' => 'fa-chain'];
            $listButtonArr[] = ['id' => 'bt_list_disable', 'text' => '禁用', 'icon' => 'fa-chain-broken'];
        }
        if (UserPower::checkUserPower('User_UserList_Group')) {
            $listButtonArr[] = ['id' => 'bt_list_group', 'text' => ' 设置组', 'icon' => 'fa-pencil'];
        }
        if (UserPower::checkUserPower('User_UserList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('User_UserList_SetPower')) {                                                      //未配置权限，超级管理员才可使用
            $listButtonArr[] = ['id' => 'bt_list_power', 'text' => '设置权限', 'icon' => 'fa-pencil'];
        }
        if (UserPower::checkUserPower('User_UserList_ViewPower')) {
            $listButtonArr[] = ['id' => 'bt_list_view_power', 'text' => '查看权限', 'icon' => 'fa-eye'];
        }
        if (UserPower::checkUserPower('User_UserList_Assist')) {
            $listButtonArr[] = ['id' => 'bt_list_assist', 'text' => '协助', 'icon' => 'fa-user-secret'];
        }
        if ($userType == 5) {
            $listButtonArr[] = ['id' => 'bt_list_seeBindStu', 'text' => '查看绑定学生', 'icon' => 'fa-eye'];
        }
//        if ($userType == 7 && UserPower::checkUserPower('User_UserList_ContactTeacher')) {
//            $listButtonArr[] = ['id' => 'bt_list_ContactTeacher', 'text' => '关联教师', 'icon' => 'fa-pencil'];
//        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_status', 'style' => 'width: 60px;', 'data' => [
            0 => '全部', 1 => '正常', 2 => '历史', 3 => '禁用', 4 => '内部'
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_create_start', 'class' => 'easyui-datebox',
            'style' => 'width: 100px;', 'label' => ' 创建： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_create_end', 'class' => 'easyui-datebox',
            'style' => 'width: 100px;', 'label' => ' ~ '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => ' 搜索： '];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search',
            'style' => 'margin-left:10px'];
        $this->userEnum['iSchoolId'] = ['' => '--请选择--'] + School::getSchools(true);

        if (UserPower::checkUserPower('User_UserList_Info')) {
            $power['info'] = Power::exist('User_UserList_Info');
        }
        if (UserPower::checkUserPower('User_UserList_Extra')) {
            $power['extra_info'] = Power::exist('User_UserList_Extra');
        }
        if (UserPower::checkUserPower('User_UserList_Device')) {
            $power['device'] = Power::exist('User_UserList_Device');
        }
        if (UserPower::checkUserPower('User_UserList_History')) {
            $power['history'] = Power::exist('User_UserList_History');
        }
        if (UserPower::checkUserPower('User_UserList_School_Edit')) {
            $power['school'] = Power::exist('User_UserList_School_Edit');
        }
        if (UserPower::checkUserPower('User_UserList_Login')) {
            $power['login'] = Power::exist('User_UserList_Login');
        }
        if (isset($power['extra_info'])) {
            $this->view->setVars([
                'ExtraFormStu' => Template::createForm('XHSys_UserStudent', $this->getUserEnum()),
                'ExtraFormTch' => Template::createForm('XHSys_UserTch', $this->getUserEnum()),
            ]);
        }
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHSys_User', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'tableAttr' => ['rownumbers' => 'false']
            ]),
            'Form' => Template::createForm('XHSys_User', $this->getUserEnum()),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('User_UserList')),
            'power' => $power
        ]);
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * create by ck 20160315
     * modify by ck 20160602
     * modify by ck 20160809    去掉userInfo表，不使用分页组件（效率低）
     * modify by ck 20161010    公共方法分页
     * modify by ck 20171130    添加正常账号筛选
     * modify by ck 20180227    添加状态筛选
     * modify by ck 20180705    添加学校
     * modify by fyh 20181214   M分层
     * modify by fyh 20190123   新增身份证号码搜索
     */
    public function getDgDataAction()
    {
        $userType = $this->request->getPost('iUserType', 'int');
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $normal   = $this->request->getPost('normal', 'string');
        $search   = $this->request->getPost('search');
        $status   = $this->request->getPost('status', 'int');
        $startDate = $this->request->getPost('startDate', 'string');
        $endDate  = $this->request->getPost('endDate', 'string');
        try {
            $UserManage = new UserManage();
            $data = $UserManage->getDgData($userType, $schoolId, $normal, $status, $startDate, $endDate, $search);
            return $this->sendJsonResponse($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 添加用户页面
     *
     * create by fyh 20190214
     */
    public function addUserAction()
    {
        $this->view->pick('user/addUser');
        Assets::select2();
        Assets::easyUI('js/user/addUser.js');
        $this->userEnum['iSchoolId'] = ['' => '--请选择--'] + School::getSchools(true);
        return $this->view->setVars([
            'Form' => Template::createForm('XHSys_User', $this->getUserEnum()),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('User_UserList')),
        ]);
    }
    /**
     * 根据用户id获取信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171227
     * modify by fyh 20181214
     */
    public function getUserInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        $userType = $this->request->getPost('userType');
        $schoolId = $this->request->getPost('schoolId');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少ID');
        }
        if (!$userType) {
            return $this->sendErrorResponse(400, '缺少用户类型');
        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校ID');
        }
        $extraInfo = [];
        $power['btn'] = "";
        if (UserPower::checkUserPower('User_UserList_School')) {
            $power['btn'].= "<a id=\"setSchool\"  class=\"btn btn-sm btn-default pull-right return\" 
style=\"margin-right: 20px\">修改学校</a>";
        }
        if (UserPower::checkUserPower('User_UserList_Psw')) {
            $power['btn'].= "<a id=\"setPsw\"  class=\"btn btn-sm btn-default pull-right return\" 
style=\"margin-right: 20px\">重置密码</a>";
        }
        if (UserPower::checkUserPower('User_UserList_Group')) {
            $power['btn'].= "<a id=\"setGroup\"  class=\"btn btn-sm btn-default pull-right return\" 
style=\"margin-right: 20px\">设置分组</a>";
        }
        if ($userType == '学生') {
            $extraInfo = XhsysUser::getStudentInfoByUserId($id, $schoolId);
        }
        if ($userType == '教师') {
            $extraInfo = XhsysUserTch::getTchInfoByUserId($id);
        }
        try {
            $user = UserManage::getUserInfo($id);
            $info = array_merge($user, $extraInfo, $power);
            return $this->sendJsonResponse($info);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 插入，修改数据
     *
     * create by ck 20160304
     * modify by ck 20160630    优化
     * modify by ck 20161010    创建modal化简
     * modify by ck 20161020    添加判断用户名是否重复步骤
     * modify by ck 20161203    编辑管理员/超管时判断用户身份
     * modify by ck 20171227
     * modify by ck 20180514    同步处理老库
     * modify by fyh 20181214
     */
    public function modifyUserAction()
    {
        $sLogonName = $this->request->getPost('sLogonName', 'string');
        $data = $this->request->getPost();
        try {
            $msg = '操作成功';
            UserManage::modifyUser($data, $sLogonName);
            if ($data['iUserId']) {
                if (UserPower::checkUserPower('User_UserList_Extra_Edit')) {
                    XhsysUser::updateUserInfo($data);
                    $msg = "操作成功";
                } else {
                    $msg = "基本信息操作成功，附加信息无权限";
                }
            }
            return $this->sendSuccessResponse($msg);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 根据传入id字符串，根据逗号分割后删除记录
     *
     * create by ck 20160304
     * modify by ck 20160630    优化
     * modify by ck 20161010    结构更改
     * modify by ck 20171227    结构更改
     * modify by fyh 20181214
     */
    public function delUserAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!UserPower::checkUserPower('User_UserList_Del')) {
            return $this->sendErrorResponse(403, '无删除权限');
        }
        try {
            UserManage::delUser($ids);
            return $this->sendSuccessResponse('成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 设置用户状态（启用/禁用）
     *
     * create by ck 20160630
     * modify by ck 20161014
     * modify by ck 20171227    更改结构
     */
    public function setUserStateAction()
    {
        $ids    = $this->request->getPost('ids', 'int');
        $target = $this->request->getPost('target', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        switch ($target) {
            case 'enable':
                $statusCondition = 'bDisable = 0';
                break;
            case 'disable':
                $statusCondition = 'bDisable = 1';
                break;
            default:
                return $this->sendErrorResponse(400, '目标操作不正确');
        }
        if (is_array($ids)) {
            $ids = implode(',', $ids);
        }
        try {
            $UserManage = new UserManage();
            $UserManage->setUserState($statusCondition, $ids);
            return $this->sendSuccessResponse('成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 批量设置密码
     *
     * create by ck 20160707
     * modify by ck 20170927
     * modify by ck 20171208    同步更新老后台
     * modify by ck 20171213    刷新登陆服务器
     * modify by dale 20180205  使用公共方法
     */
    public function setPasswordAction()
    {
        $userIds  = $this->request->getPost('userIds', 'int');
        $password = $this->request->getPost('password', 'string');
        $resetComplete = $this->request->getPost('resetComplete', 'int', 0);
        if (!$userIds || !$password) {
            return $this->sendErrorResponse(400, '参数不完整');
        }
        try {
            User::setPassword($userIds, $password, false, !!$resetComplete);
            return $this->sendSuccessResponse('修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }


    /**
     * function explain
     *
     * @param bool $view
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20160825
     * modify by ck 20180817
     */
    public function userSetPowerAction($view = false)
    {
        $this->view->pick('user/userSetPower');
        $this->assets->addJs('assets/jquery/jquery.form.js');
        Assets::importJs('js/user/userSetPower.js');
        $userId = $this->request->getQuery('iUserId');
        if (!$userId) {
            return $this->sendViewError('缺少用户id');
        }
        if ($view) {
            $this->view->setVar('viewOnly', true);
        }
        try {
            //查询用户组
            $result = UserManage::userSetPower($userId, $view);
            if ($result['groups']) {
                $this->view->setVar('groups', $result['groups']);
            }
            return $this->view->setVar('powerTree', $result['powerTree']);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 设置用户权限
     *
     * create by ck 20160829
     * modify by ck 20160830
     * modify by ck 20180606    重构
     */
    public function setUserPowerAction()
    {
        $userId    = $this->request->getPost('userId', 'int');
        $powerTags = $this->request->getPost('powerTag', 'string');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            //查询用户组
            UserManage::setUserPower($userId, $powerTags);
            return $this->sendSuccessResponse('保存成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 根据身份证号查找用户信息，有则返回ID，否则返回fail
     *
     * modify by ck 20160908
     */
    public function selectUserByIdentityAction()
    {
        $this->view->disable();
        $identityCode = $this->request->getPost('sIdentityCode', 'string');
        $user = XhsysUser::selectUserByIdentity($identityCode);
        echo $user ? $user->iUserId : 'fail';
    }

    /**
     * 设置为历史账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171123
     */
    public function setHistoryAction()
    {
        $userIds = $this->request->getPost('ids', 'int');
        $history = $this->request->getPost('history', 'string') == 'true' ? 1 : 0;
        $type = $this->request->getPost('type', 'int');
        if (!$userIds) {
            return $this->sendErrorResponse(400, '用户不能为空');
        }

        try {
            //查询用户组
            $UserManage = new UserManage();
            $UserManage->setHistory($userIds, $history);

            XhsysUserstud::find([
                'conditions' => "iUserId in ({ids:array})",
                'bind' => ['ids' => $userIds]
            ])->update(['iHistoryType' => $type]);

            return $this->sendSuccessResponse('设置成功');
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }


    public static function getGradeCode($gradeName)
    {
        switch ($gradeName) {
            case '七年级':
            case '初一':
                return 21;
            case '八年级':
            case '初二':
                return 22;
            case '九年级':
            case '初三':
                return 23;
            default:
                return null;
        }
    }

    /**
     * 重复登陆列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180120
     * modify by ck 20180831    重构
     */
    public function repeatLoginAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/user/repeatLogin.js');
        $listSearchArr = $listButtonArr = [];
        if (!UserPower::checkUserPower('User_Repeat')) {
            return $this->sendViewError('无查看权限');
        }
        if (UserPower::checkUserPower('User_Repeat_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus'];
        }
        if (UserPower::checkUserPower('User_Repeat_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_enable', 'text' => '启用', 'icon' => 'fa-link'];
            $listButtonArr[] = ['id' => 'bt_list_disable', 'text' => '禁用', 'icon' => 'fa-unlink'];
        }
        if (UserPower::checkUserPower('User_Repeat_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_logonName', 'label' => '登陆名：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_school', 'label' => ' 学校：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_startTime', 'class' => 'easyui-datebox', 'label' => ' 时间：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_endTime', 'class' => 'easyui-datebox', 'label' => ' ~ '];
        return $this->view->setVars([
            'List'  => Template::createList('list', 'User_Repeat', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取重复登陆列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180120
     * modify by ck 20180831    重构
     */
    public function getRepeatLoginAction()
    {
        try {
            $page       = $this->request->getPost('page', 'int');
            $rows       = $this->request->getPost('rows', 'int');
            $logonName  = $this->request->getPost('logonName', 'string');
            $school     = $this->request->getPost('school', 'string');
            $startTime  = $this->request->getPost('startTime', 'string');
            $endTime    = $this->request->getPost('endTime', 'string');
            if (!UserPower::checkUserPower('User_Repeat')) {
                return $this->sendDataGridError('无查看权限');
            }
            $search = [];
            if ($logonName) {
                $search['logonName'] = $logonName;
            }
            if ($startTime) {
                $search['startTime'] = strtotime($startTime);
            }
            if ($endTime) {
                $search['endTime'] = strtotime($endTime . ' +1 day');
            }
            if ($school) {
                $schoolIds = School::searchSchool($school);
                if (!$schoolIds) {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }
                $search['schoolIds'] = implode(',', $schoolIds);
            }
            return $this->sendJsonResponse(Auth::getRepeatLogin($page, $rows, $search));
        } catch (\Exception $e) {
            return $this->sendDataGridError($e->getMessage());
        }
    }

    /**
     * 删除重复登陆
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180831
     */
    public function delRepeatLoginAction()
    {
        if (!UserPower::checkUserPower('User_Repeat_Del')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $userId = $this->request->getPost('userId', 'int');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        try {
            Auth::delRepeatLogin($userId);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 添加可重复登陆用户，已有则更新时间
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180125
     * modify by ck 20180831    重构
     */
    public function createRepeatLoginAction()
    {
        if (!UserPower::checkUserPower('User_Repeat_Add')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $logonNames = $this->request->getPost('logonNames', 'string');
        $timeLimit  = $this->request->getPost('timeLimit', 'int');
        $logonNames = explode(',', $logonNames);
        if (!$logonNames) {
            return $this->sendErrorResponse(400, '登录名不能为空');
        }
        switch ($timeLimit) {
            case 1:
                $deadTime = strtotime('+1 day');
                break;
            case 2:
                $deadTime = strtotime('+1 week');
                break;
            case 3:
                $deadTime = strtotime('+1 month');
                break;
            case 4:
                $deadTime = 253402185600;
                break;
            default:
                return $this->sendErrorResponse(400, '参数错误');
        }
        try {
            Auth::createRepeatLogin($logonNames, $deadTime);
            return $this->sendSuccessResponse('添加成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 启用/禁用重复登陆
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180901
     */
    public function setRepeatLoginStateAction()
    {
        if (!UserPower::checkUserPower('User_Repeat_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $userId = $this->request->getPost('userId', 'int');
        $target = $this->request->getPost('target', 'string');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            switch ($target) {
                case 'enable':
                    Auth::enableRepeatLogin($userId);
                    break;
                case 'disable':
                    Auth::disableRepeatLogin($userId);
                    break;
                default:
                    return $this->sendErrorResponse(400, '目标操作不正确');
            }
            return $this->sendSuccessResponse('操作成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 在线列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180814
     */
    public function onlineAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/user/online.js');
        if (!UserPower::checkUserPower('userOnline')) {
            return $this->sendViewError('无查看权限');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_vague', 'label'=>'搜索： '];
        return $this->view->setVars([
            'List'  => Template::createList('list', 'User_Online', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr),
            ]),
        ]);
    }

    /**
     * 获取在线列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180814
     */
    public function getOnlineAction()
    {
        try {
            $data = UserManage::getOnline();
            return $this->sendJsonResponse($data);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
    * 设备使用
    *
    * @return string
    *
    * create by ck 20190107
    */
    public function deviceAction()
    {
        $userId = $this->request->getQuery('userId');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        Assets::select2();
        Assets::easyUI('js/user/userDevice.js');
        $this->view->pick('user/userDevice');
        try {
            $current = Device::getBoundByUserId($userId);
            if (!empty($current['nowUseInfo'])) {
                $this->view->setVars([
                    'sDevNumber' => $current['nowUseInfo']['sDevNumber'],
                    'tNowReceiveTime' => $current['nowUseInfo']['tNowReceiveTime'],
                    'iReceivePurpose' => $current['nowUseInfo']['iReceivePurpose'],
                ]);
            }
            $this->view->setVars([
                'model' => $current['sModel'],
                'deviceNumber' => $current['sDeviceNumber'],
                'mac' => $current['sMac'],
                'createDate' => $current['tCreateDate'],
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取设备使用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by fyh 20190108
     */
    public function getDeviceAction()
    {
        $userId = $this->request->getPost('id');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            $data = Device::getDevHistoryByUserId($userId);
            foreach ($data as $k => $v) {
                if ($v['end'] == null) {
                    $data[$k]['end'] = "";
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取设备维修
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by fyh 20190108
     */
    public function getRepairAction()
    {
        $userId = $this->request->getPost('id');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            $data = Device::getRepairDevByUserId($userId);//30502 测试id
            foreach ($data as $k => $v) {
                if ($v['sNewDeviceNumber'] == null) {
                    $data[$k]['sNewDeviceNumber'] = "";
                }
                if ($v['sStartDate'] == null) {
                    $data[$k]['sStartDate'] = "";
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
    * 历史记录
    *
    * @return string
    *
    * create by ck 20190107
    */
    public function historyAction()
    {
        $userId = $this->request->getQuery('userId');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        Assets::select2();
        Assets::easyUI('js/user/userHistory.js');
        $this->view->pick('user/userHistory');
        try {
            $this->view->setVars([
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取历史记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by fyh 20190108
     */
    public function getHistoryAction()
    {
        $userId = $this->request->getPost('id');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            $data = XhsysUserHistory::getHistoryByUserId($userId);
            foreach ($data as $k => $v) {
                if ($v['tInTime'] == null) {
                    $data[$k]['tInTime'] = "";
                }
                if ($v['tOutTime'] == null) {
                    $data[$k]['tOutTime'] = "";
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
    * 登录日志
    *
    * @return string
    *
    * create by ck 20190107
    */
    public function loginAction()
    {
        $userId = $this->request->getQuery('userId');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/user/userLogin.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_start', 'label'=>' 时间：'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_end', 'label'=>' ~ '];
        try {
            $this->view->setVars([
                'List'  => Template::createList('list', 'User_Login', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr),
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取历史记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     * create by fyh 20190108
     */
    public function getLoginAction()
    {
        $userId = $this->request->getPost('userId');
        $startDate = $this->request->getPost('startDate');
        $endDate = $this->request->getPost('endDate');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            $data = UserManage::getLogin($userId, $startDate, $endDate);//32915 测试id
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 修改学校
     * @return \Phalcon\Mvc\View|string
     * create by fyh 20190108
     */
    public function setSchoolAction()
    {
        $userIds = $this->request->getQuery('userIds', 'string');
        if (!$userIds) {
            return $this->sendViewError('缺少用户id');
        }
        $this->view->pick('user/userSchool');
        Assets::select2();
        Assets::easyUI('js/user/userSchool.js');
        $this->userEnum['iSchoolId'] = ['' => '--请选择--'] + School::getSchools(true);
        return $this->view->setVars([
            'Form' => Template::createForm('XHSys_User_School', $this->getUserEnum()),
        ]);
    }

    /**
     * 修改学校
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     * create by fyh 20190111
     */
    public function modifySchoolAction()
    {
        $iUserId = $this->request->getPost('iUserId', 'int');
        $iSchoolId = $this->request->getPost('iSchoolId', 'int');
        if (!$iUserId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!$iSchoolId) {
            return $this->sendErrorResponse(400, '请选择学校');
        }
        if (!UserPower::checkUserPower('User_UserList_School_Edit')) {
            throw new XhException('无操作权限');
        }
        try {
            $data = [
                'iUserId' => $iUserId,
                'iSchoolId' => $iSchoolId,
            ];
            UserManage::modifySchool($data);
            $result['schoolName'] = XhschoolInfo::getSchoolNameById($iSchoolId);
            $result['code'] = 200;
            $result['msg'] = '成功';
            return $this->sendJsonResponse($result);
        } catch (Exception $e) {
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }
    /**
     * 同步用户中心数据
     *
     * create by ck 20161031
     * modify by ck 20161216    用户密码如果为32位长度则直接保存
     */
//    public function synUserAction()
//    {
//        $this->view->disable();
//        Main::getLoginUserInfo('logonName') or die('（109108018）无操作权限！');
//        $refreshUserConfig = Main::getConfigByName('cRelation');
//        if(isset($refreshUserConfig['refreshUser']) && !empty($refreshUserConfig['refreshUser'])){
//            echo '<br />' . @file_get_contents($refreshUserConfig['refreshUser']);
//        }
//        $oldDbConfig = $GLOBALS['configIni']->get('database')->toArray();
//        $tempConn = new \Phalcon\Db\Adapter\Pdo\Mysql([
//            'host'      => $oldDbConfig['host'],
//            'username'  => 'readonly',
//            'password'  => 'lVf641AO',
//            'dbname'    => $oldDbConfig['dbname'],
//            'charset'   => $oldDbConfig['charset']
//        ]);
//        $diffIdArr = $tempConn->fetchAll('select us_id from xh_product.users where
// us_id not in (select iUserId from xh_webmanage.XHSys_User)');
//        $diffIdArr = array_column($diffIdArr, 'us_id');
//        if(empty($diffIdArr)) die('（109108020）无差异，不需要同步！');
//        $diffIdArr = implode(',', $diffIdArr);
//        $tempConn->execute('SET NAMES "latin1"');
//        $userInfo = $tempConn->fetchAll("SELECT us_id,us_name,us_uid,us_passwd,us_tel,us_flag,
//us_xb,us_school_xxid,us_sdnj,us_szbj,us_sskm,us_mz,sPortrait,sMotherPhone,sFatherPhone,sOtherPhone,iFirstPhone,us_date
// FROM xh_product.users WHERE us_id IN ({$diffIdArr})");
//        $tempConn->execute('SET NAMES "utf8"');
//        $insertSql = 'INSERT INTO XHSys_User (iUserId,sUserName,sLogonName,sLogonPwd,sSelfPhone,
//iUserType,iUserSex,iSchoolId,iGradeCode,sAdClsName,sSubject,sNationName,sPortrait,sMotherPhone,sFatherPhone,sOtherPhone,
//iFirstPhone,bCompany,bDisable,bOldData,bDelete,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId) VALUES ';
//        $valueArr = [];
//        $nowTime = date('Y-m-d H:i:s');
//        $userId = Main::getLoginUserInfo('userId');
//        foreach($userInfo as $user){
//            $user['us_passwd']  = strlen($user['us_passwd']) == 32 ? $user['us_passwd'] : strtoupper(md5($user['us_passwd']));
//            $user['us_xb']      = $user['us_xb'] == '男' ? 1 : ($user['us_xb'] == '女' ? 2 : 0);
//            $user['us_sdnj']    = self::getGradeCode($user['us_sdnj']);
//            $valueArr[] = "('{$user['us_id']}','{$user['us_name']}','{$user['us_uid']}','{$user['us_passwd']}','{$user['us_tel']}','{$user['us_flag']}','{$user['us_xb']}','{$user['us_school_xxid']}','{$user['us_sdnj']}','{$user['us_szbj']}','{$user['us_sskm']}','{$user['us_mz']}','{$user['sPortrait']}','{$user['sMotherPhone']}','{$user['sFatherPhone']}','{$user['sOtherPhone']}','{$user['iFirstPhone']}',0,0,1,0,'{$user['us_date']}',{$userId},'{$nowTime}',{$userId})";
//        }
//        $insertSql .= implode(',', $valueArr);
//        $this->db->query($insertSql) or die('插入失败！');
//        echo '执行成功！成功插入' . count($valueArr) . '条';
//    }


    /**
     * 学校列表扩展权限页面
     *
     * create by ck 20160906
     * modify by ck 20161122
     * modify by ck 20161226    判断已有权限，传递给前台js变量，默认选中
     * modify by ck 20180108    结构更改
     */
//    public function extraSchoolListAction()
//    {
//        $this->view->pick('user/extraSchoolList');
//        Assets::easyUI('js/user/extraSchoolList.js');
//        $userId = $this->request->getQuery('userId', 'int');
//        if (!$userId) {
//            return $this->sendViewError('缺少用户id');
//        }
//        $viewSearchArr = $manageSearchArr = [];
//        $viewSearchArr[]    = ['type'=>'text', 'id'=>'list_view_vague', 'label'=>'搜索： '];
//        $viewSearchArr[]    = [
//'type'=>'button','id'=>'bt_list_view_search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
//        $manageSearchArr[]  = ['type'=>'text', 'id'=>'list_manage_vague', 'label'=>'搜索： '];
//        $manageSearchArr[]  = [
//'type'=>'button','id'=>'bt_list_manage_search', 'text'=>'确定', 'icon'=>'fa-search', 'style'=>'margin-left:10px'];
//        return $this->view->setVars([
//            'ViewList'      => Template::createList('view_list', 'XHSchool_Info', [
//                'title'         => '设置查看列表',
//                'tableAttr'     => ['pagination' => 'false'],
//                'searchToolbar' => Template::createSearchToolBar($viewSearchArr)
//            ]),
//            'ManageList'    => Template::createList('manage_list', 'XHSchool_Info', [
//                'title'         => '设置管理列表',
//                'tableAttr'     => ['pagination' => 'false'],
//                'searchToolbar' => Template::createSearchToolBar($manageSearchArr)
//            ]),
//            'isAdmin'       => User::isAdmin()
//        ]);
//    }

    /**
     * 设置扩展权限
     *
     * create by ck 20160906
     * modify by ck 20180108    更改结构
     */
//    public function setExtraPowerAction()
//    {
//        $userId             = $this->request->getPost('userId', 'int');
//        $target             = $this->request->getPost('target', 'string');
//        $viewJson           = $this->request->getPost('view');
//        $manageJson         = $this->request->getPost('manage');
//        $viewJson['id']     = implode(',', $viewJson['id']);
//        $manageJson['id']   = implode(',', $manageJson['id']);
//        if (!XhsysUserpower::createExtraRecord($userId, $target, $viewJson, $manageJson)) {
//            return $this->sendErrorResponse(500, '保存失败');
//        }
//        UserPower::delPowerCache('school', $userId);
//        return $this->sendSuccessResponse('保存成功');
//    }


    /**
     * 检查用户名是否重复
     *
     * create by ck 20160318
     * modify by ck 20160630
     */
//    public function checkUserLogonNameAction()
//    {
//        $this->view->disable();
//        $logonName = $this->request->getPost('logonName', 'string');
//        $user = XhsysUser::findFirst("sLogonName = '{$logonName}' AND bDelete = 0");
//        echo $user ? 'error' : 'success';
//    }

    /**
     * 根据用户ID修改用户姓名
     *
     * create by ck 20160707
     */
//    public function setUserNameAction()
//    {
//        $this->view->disable();
//        $userId   = $this->request->getPost('iUserId', 'int');
//        $userName = $this->request->getPost('sUserName', 'string');
//        $user = XhsysUser::findFirst(array(
//            'conditions' => "bDelete=0 AND iUserId = $userId"
//        ));
//        $user or die('（109108009）服务器错误，无此用户信息！');
//        $user->sUserName = $userName;
//        $result = $user->updateData();
//        $result or die('（109108010）服务器错误，操作失败！');
//        Main::createCommitLog('user', 'User', 'edit', $user, $userId, '修改姓名');
//        echo '操作成功！';
//    }

    /**
     * 显示学校列表(供新增学生及教师选择学校)
     *
     * create by ck 20160318
     * modify by ck 20160913    结构更改
     */
//    public function userChooseSchoolAction()
//    {
//        $this->view->pick('user/userChooseSchool');
//        Assets::easyUI('js/user/userChooseSchool.js');
//        $this->view->setVars(array(
//            'List'  => Template::createList('List', 'XHSchool_Info', array('checkbox' => false))
//        ));
//    }


    /**
     * 根据学校选择教师页面
     *
     * create by ck 20160726
     */
//    public function userSchoolTeacherListAction()
//    {
//        $this->view->pick('user/userSchoolTeacherList');
//        Assets::easyUI('js/user/userSchoolTeacherList.js');
//        UserPower::checkUserPower('User_UserList_ContactTeacher')
//            or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109108013));
//        Template::exists('XHSchool_Info_List', 'list') && Template::exists('XHSchool_User', 'list')
//            or die(Main::showMessageModal('列表配置文件不存在，请先创建！',109108014));
//        $this->view->setVars(array(
//            'SchoolList'    => Template::createList('SchoolList', 'XHSchool_Info', ['checkbox' => false]),
//            'TeacherList'   => Template::createList('TeacherList', 'XHSchool_User', [
//'tableAttr'=>['singleSelect'=>false]])
//        ));
//    }

    /**
     * 服务人员关联教师
     *
     * create by ck 20160726
     */
//    public function contactServerTeacherAction()
//    {
//        $this->view->disable();
//        $this->request->isPost() or die;
//        UserPower::checkUserPower('User_UserList_ContactTeacher')
//            or die(Main::showMessageModal('没有操作权限！', 109108015));
//        $serverId = $this->request->getPost('iUserId', 'int');
//        $teacherIds = explode(',', $this->request->getPost('sTeacherIds'));
//        $teacherIds or die(Main::showMessageModal('教师不能为空！', 109108016));
//        $dbRollback = false;
//        $this->db->begin();
//        foreach($teacherIds as $teacherId){
//            $obj = XhsysServerteacher::getRecord($serverId,$teacherId);
//            if(!$obj) continue;
//            if(!$obj->insertData()){
//                $dbRollback = true;
//                goto dealTrans;
//            }
//        }
//        dealTrans:
//        if($dbRollback){
//            $this->db->rollback();
//            die('（109108017）操作失败！');
//        }
//        Main::createCommitLog('user', 'userSchoolTeacherList', 'contact',
// ['iUserId'=>$serverId,'sTeacherIds'=>$teacherIds], $serverId);
//        $this->db->commit();
//        echo '操作成功！';
//    }

}

